<template>
  <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false" v-model="dialogModelValue" title="签约协议" width="850px" :before-close="handleClose">
    <el-steps :active="active" align-center>
      <el-step title="签署平台协议" />
      <el-step title="重置平台登录密码" />
      <el-step title="设置支付密码" />
    </el-steps>
    <div v-if="active === 1" style="min-height: 400px;overflow-y: auto;" v-html="pcLoginProtocol"></div>
    <div v-if="active === 2" style="padding: 20px 0;">
      <el-form ref="pwdRef" :model="user" :rules="rules" label-width="100px" label-suffix=":">
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input v-model="user.oldPassword" placeholder="请输入旧密码" type="password" :show-password="true" />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="user.newPassword" placeholder="请输入新密码" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="user.confirmPassword" placeholder="请输入确认密码" type="password" show-password />
        </el-form-item>
        <div style="display: flex;justify-content: center;">
          <el-button @click="logout" plain type="danger" >退出登录</el-button>
          <el-button type="primary" @click="submit" :loading="loading"> 确定 </el-button>
        </div>
      </el-form>
    </div>
    <div v-if="active === 3" style="padding: 20px 0;">
      <el-form ref="payPwdRef" :model="userPay" :rules="rulesPay" label-width="100px" label-suffix=":">
        <el-form-item label="支付密码" prop="oldPassword">
          <el-input v-model="userPay.oldPassword" placeholder="请输入支付密码" type="password" :show-password="true" />
        </el-form-item>
        <el-form-item label="验证码" prop="newPassword">
          <el-input v-model="userPay.newPassword" type="number" placeholder="请输入验证码" >
            <template #append>
              <el-button @click="sendSmsCode" >{{sendTxt.txt}}</el-button>
              </template>
          </el-input>
        </el-form-item>
        <div style="width:30%;margin:auto;">
          <el-button type="danger" plain @click="logout">退出登录</el-button>
          <el-button type="primary" @click="submitPayPwd" :loading="loading">确定</el-button>
        </div>
      </el-form>
    </div>
    <template #footer v-if="active === 1">
      <div>
        <el-checkbox v-model="hadRead" label="Option 2">我已阅读并同意 《平台使用协议》</el-checkbox>
      </div>
      <el-button type="danger" plain  @click="logout">暂不签约，退出</el-button>
      <el-button type="primary" @click="confirm" :disabled="!hadRead">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import useAppStore from '@/store/modules/app';
import { useUserStore } from '@/store/modules/user'
import type { FormInstance, FormRules } from 'element-plus'
import {sendPaySmsCode,updReadTag,resetMyPwd,resetPayPwd} from '@/api/system/user/index'
import type { ResetPwdForm } from "@/api/system/user/types";
const userStore = useUserStore()
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const emit = defineEmits(['update:modelValue'])

const dialogModelValue = ref(false);

const user = ref<ResetPwdForm>({
  oldPassword: "",
  newPassword: "",
  confirmPassword: ""
});

const userPay = ref<ResetPwdForm>({
  oldPassword: "",
  newPassword: "",
  confirmPassword: ""
});

const sendTxt = ref({
    txt:"获取验证码",
    countdown:60,
    getSmsCodeStatus:false
});


const startCountdown = function() {

let countdown = sendTxt.value.countdown;
  const intervalId = setInterval(() => {
    countdown--;
    sendTxt.value.countdown = countdown;
    sendTxt.value.txt = sendTxt.value.countdown+'秒后重新获取';
    if (countdown <= 0) {
      clearInterval(intervalId);
      sendTxt.value.countdown = 60;
      sendTxt.value.getSmsCodeStatus = false;
      sendTxt.value.txt ="获取验证码";
    }
  }, 1000);
};


const sendSmsCode = ()=>{
    if(sendTxt.value.getSmsCodeStatus){
      return ;
    }
    sendTxt.value.getSmsCodeStatus = true;
    sendSms();
}


const sendSms = async()=>{
      let domain = window.location.origin;
      try{
         sendTxt.value.txt = sendTxt.value.countdown+'秒后重新获取';
         startCountdown();
        let rep =  await sendPaySmsCode(domain);
        if(rep.code == 200){
          proxy?.$modal.msgSuccess("发送成功");
        }else{
          proxy?.$modal.msgError("发送失败");
        }
      }catch(e){
          sendTxt.value.getSmsCodeStatus = false;
      }
}






const rulesPay = ref({
  oldPassword: [{ required: true, message: "支付密码不能为空", trigger: "blur" }, {
    min: 6,
    max: 20,
    message: "长度在 6 到 20 个字符",
    trigger: "blur"
  }],
  newPassword: [{ required: true, message: "验证码不能为空", trigger: "blur" }]
});



const loading = ref(false);

const equalToPassword = (rule: any, value: string, callback: any) => {
  if (user.value.newPassword !== value) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};
const rules = ref({
  oldPassword: [{ required: true, message: "旧密码不能为空", trigger: "blur" }],
  newPassword: [{ required: true, message: "新密码不能为空", trigger: "blur" }, {
    min: 6,
    max: 20,
    message: "长度在 6 到 20 个字符",
    trigger: "blur"
  }],
  confirmPassword: [{ required: true, message: "确认密码不能为空", trigger: "blur" }, {
    required: true,
    validator: equalToPassword,
    trigger: "blur"
  }]
});

const logout = async () => {
    await userStore.logout()
    emit('update:modelValue', false)
    location.href = import.meta.env.VITE_APP_CONTEXT_PATH + 'index';
}

const pwdRef = ref<FormInstance>();
const payPwdRef = ref<FormInstance>();

/** 提交按钮 */
const submit = () => {
  pwdRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try{
        loading.value = true;
        await resetMyPwd(user.value.oldPassword, user.value.newPassword,user.value.confirmPassword);
        loading.value = false;
        proxy?.$modal.msgSuccess("重置成功");

        if(userStore.curRoleId == 8){
           dialogModelValue.value = false;
           emit('update:modelValue', false)
        }else{
            active.value = 3;
        }

      }catch(e){
        loading.value = false;
      }
    }
  });
};


/** 提交按钮 */
const submitPayPwd = () => {
  payPwdRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try {
        loading.value = true;
        await resetPayPwd(userPay.value.oldPassword, userPay.value.newPassword);
        loading.value  = false;
        proxy?.$modal.msgSuccess("设置成功");
        dialogModelValue.value = false;
        emit('update:modelValue', false)
      }catch(e){
         loading.value  = false;
      }
    }
  });
};

const hadRead = ref<boolean>(false)
const active = ref(1)


const appStore = useAppStore();
const webSiteInfo = computed(() => appStore.webSiteInfo)
const pcLoginProtocol = computed(() => webSiteInfo.value.pcLoginProtocol)

const handleClose = (done: () => void) => {
  if (hadRead.value) {
    done()
  } else {
    ElMessageBox.confirm('请先阅读《平台使用协议》并同意签约')
  }
}

interface Props {
    modelValue: boolean,
    activeTab:number

}

const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    activeTab:1,
    tableData: () => [],
});

active.value = props.activeTab;

const confirm = () => {

  updReadTag().then(res=>{
      if(res.code == 200){
        active.value = 2
      }
  })

}


watch(() => props.activeTab, (value) => {
  active.value = value;
})
watch(() => props.modelValue, (value) => {
  dialogModelValue.value = value;
})



</script>
